<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <el-form :model="queryParams" ref="queryForm" :inline="true"  v-show="showSearch" label-width="80px">
          <el-form-item label="模板名称" prop="templateName">
            <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" size="small" clearable style="width: 150px"/>
          </el-form-item>
          <el-form-item label="模板编码" prop="templateCode">
            <el-input v-model="queryParams.templateCode" placeholder="请输入模板编码" size="small" clearable style="width: 150px"/>
          </el-form-item>
   <!--       <el-form-item label="模板内容" prop="content">
            <el-input v-model="queryParams.content" placeholder="请输入模板内容" size="small" clearable style="width: 150px"/>
          </el-form-item>-->
          <el-form-item label="模板签名" prop="templateSign">
            <el-input v-model="queryParams.templateSign" placeholder="请输入模板签名" size="small" clearable style="width: 150px"/>
          </el-form-item>
          <el-form-item label="发送渠道" prop="channelName">
            <el-input v-model="queryParams.channelName" placeholder="请输入发送渠道" size="small" clearable style="width: 150px"/>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary"  v-hasPermi="['saveSmsTemplate']"  icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" v-hasPermi="['updateSmsTemplate']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" v-hasPermi="['deleteSmsTemplate']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="querySmsTemplatePageResList" :columns="columns"></right-toolbar>
        </el-row>
        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                    @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center"/>
          <el-table-column label="模板名称" align="left" prop="templateName"/>
          <el-table-column label="模板编码" align="left" prop="templateCode"/>
          <el-table-column label="模板内容" align="left" prop="content" :show-overflow-tooltip="true"/>
          <el-table-column label="模板签名" align="left" prop="templateSign"/>
          <el-table-column label="发送渠道" align="left" prop="channelName"/>
          <el-table-column label="创建部门" align="left" prop="createDeptName"/>
          <el-table-column label="创建时间" align="center" prop="createTime" sortable='custom' width="200" />
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateSmsTemplate']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" v-hasPermi="['deleteSmsTemplate']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0"  :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows" @pagination="querySmsTemplatePageResList"/>
      </el-col>
    </el-row>


    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.templateName" placeholder="请输入模板名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="模板编码" prop="templateCode">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.templateCode" placeholder="请输入模板编码,只能填写英文字母" maxlength="200" />
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.content" placeholder="请输入模板内容" maxlength="200" />
        </el-form-item>
        <el-form-item label="模板签名" prop="templateSign">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.templateSign" placeholder="请输入模板签名,只能填写中文英文数字下划线和【】" maxlength="50" />
        </el-form-item>

        <el-form-item label="发送渠道" prop="channelName">
          <el-input v-model="form.channelName" readonly placeholder="请点击右侧按钮选择发送渠道">
            <template slot="append">
              <el-button type="primary" @click="smsChannelOpen">
                选择发送渠道
                <i class="el-icon-message el-icon--right"></i>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <el-descriptions :colon=false>
        <el-descriptions-item > <el-tag size="small">温馨提示：所有短信模板必须到对应的服务商先报备并审核通过后，再到此处添加后才能进行短信发送。</el-tag></el-descriptions-item>
      </el-descriptions>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 短信发送渠道选择组件 -->
    <SelectSmsChannel ref="selectSmsChannel" @handleSelectSmsChannel="selectSmsChannel" />

  </div>
</template>

<script>
  import SelectSmsChannel from '@/components/DuoJuHe/Common/SelectSmsChannel'
  import {querySmsTemplatePageResList, saveSmsTemplate, updateSmsTemplate, deleteSmsTemplateByTemplateId} from '@/api/sms/smsTemplate'
  //默认查询参数
  let defaultQueryParams = {
    templateName: undefined,
    startTime: undefined,
    endTime: undefined,
    content: undefined,
    templateCode: undefined,
    createDeptId: undefined,
    templateSign: undefined,
    channelName: undefined,
    page: 1,
    rows: 10
  }
  export default {
    name: 'smsTemplateAdmin',
    components: {
      SelectSmsChannel
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        //操作短信模板
        dataList: [],
        // 日期范围
        dateRange: [],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //列信息
        columns: [],
        // 新增修改表单校验
        addUpdateOpenRules: {
          templateName: [
            { required: true, message: "模板名称不能为空",trigger: "blur" },
          ],
          channelName: [
            { required: true, message: "模板发送渠道必须选择"},
          ],
          templateCode: [
            { required: true, message: "模板编码不能为空",trigger: "blur" },
            { validator: this.formValidate.enNO,trigger: "blur"}
          ],
          content: [
            { required: true, message: "模板内容不能为空",trigger: "blur" },
          ],
          templateSign: [
            { required: true, message: "模板签名不能为空",trigger: "blur" },
            { validator: this.formValidate.smsSign,trigger: "blur"}
          ]
        }
      }
    },
    created() {
      this.querySmsTemplatePageResList()
    },
    methods: {
      //选择短信渠道组件内容
      selectSmsChannel(payload) {
        this.$set(this.form, "channelId", payload.channelId)
        this.$set(this.form, "channelName", payload.channelName)
      },
      //打开短信发送渠道选择组件
      smsChannelOpen() {
        this.$refs.selectSmsChannel.selectSmsChannelOpen()
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.templateId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column) {
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.querySmsTemplatePageResList()
      },
      /** 查询短信模板列表 */
      querySmsTemplatePageResList() {
        this.loading = true
        querySmsTemplatePageResList(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
            this.dataList = res.data.records
            this.total = res.data.total
          }
        ).finally(() => {
          //关闭加载特效
          this.loading = false
        })
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.addUpdateOpen = true;
        this.title = "添加模板";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.form = {...row};
        this.addUpdateOpen = true;
        this.title = "修改模板";
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选模板?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const templateId={templateId:row.templateId}
          return deleteSmsTemplateByTemplateId(templateId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.querySmsTemplatePageResList();
        }).catch(function() {});
      },

      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.templateId !== undefined) {
              updateSmsTemplate(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.querySmsTemplatePageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveSmsTemplate(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.querySmsTemplatePageResList();
                this.addUpdateOpen = false
              });
            }
          }
        });
      },

      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = []
        this.resetForm(fromId)
        this.handleQuery()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.querySmsTemplatePageResList()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.form = {
          templateId: undefined,
          templateName: undefined,
          templateCode: undefined,
          templateSign: undefined,
          channelName: undefined,
          content: undefined
        };
        this.resetForm('form')
      }
    }
  }
</script>
